<template>
	<view class="content" :style="{ marginTop: barTop + 'rpx' }">
		<view style="font-size: 25px;">
			记录我的生活
		</view>
		<view style="display: flex;justify-content: space-between;height: 5%;align-items: center;">
			<view>
				<text style="font-size: 16px;" @click="confirm">取消</text>
			</view>
			<view>
				<button
					style="height: 80%;width: 100%;font-size: 16px;display: flex;align-items: center;background-color: #67C23A ;color: #FFF;"
					@click="submit">发布</button>
			</view>
		</view>
		<view style="height: 90%;width: 100%;">
			<view style="width: 100%;margin: 5% 0;">
				<!-- <u-input v-model="value" :type="textarea" :border="false" height="100rpx" placeholder="这一刻的想法..." auto-height="true"/> -->
				<textarea v-model="value" placeholder-style="color:#bdbdbd;" auto-height placeholder="这一刻的想法..."
					style="width:100%;height: 400rpx;" />
			</view>
			<view v-if="isPlaying">
				<video ref="videoPlayer" :src="videoFileUrl" :play-btn-position="center" :loop="true" :autoplay="false"
					:enable-play-gesture="true">
				</video>
			</view>
			<view v-else>
				<u-upload ref="uUpload" :action="action" :auto-upload="true" :header="header"></u-upload>
			</view>

			<view style="margin-top: 5%;">
				<u-cell-group>
					<u-cell-item icon="trash-fill" title="移除视频" :border-top="true" bg-color="#f1f1f1;"
						@click="removeVideo()" v-if="isPlaying"></u-cell-item>
					<u-cell-item icon="camera-fill" title="上传视频" :border-top="true" bg-color="#f1f1f1;"
						@click="getVideo()"></u-cell-item>
					<u-cell-item icon="map" title="当前所在位置" :border-top="true" bg-color="#f1f1f1;" :value="locationInfo"
						@click="getCurrentLocation()"></u-cell-item>
					<u-cell-item icon="weixin-fill" title="提醒谁看" :border-top="true" bg-color="#f1f1f1;"
						@click="getCurrentLocation()"></u-cell-item>
				</u-cell-group>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/config'
	import {
		getToken
	} from '@/utils/auth'
	import {
		addDaily
	} from '@/api/bot/daily'
	export default {
		data() {
			return {
				barTop: 0,
				groupId: '',
				value: '',
				action: config.baseUrl + '/common/upload',
				header: '',
				locationInfo: '',
				locationDetail: '',
				videoFilePath: '',
				videoFileUrl: '',
				videoFile: {
					newFileName: '',
					fileName: ''
				},
				isPlaying: false,
				self: null // 添加一个变量来保存组件实例的引用
			}
		},
		created() {
			// 1.获取屏幕可使用宽度
			let windowWidth = uni.getSystemInfoSync().windowWidth;
			// 2.获取状态栏高度
			const statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
			// 3.获取胶囊按钮位置信息
			const menuButton = uni.getMenuButtonBoundingClientRect();
			// 4.计算出导航栏高度  换算成rpx
			let navHeight = (menuButton.height + (menuButton.top - statusBarHeight) * 2) * (750 / windowWidth);
			// 5.导航栏与状态栏拉开距离  margin-top: statusBarTop + 'rpx'; 
			const statusBarTop = statusBarHeight * (750 / windowWidth);
			this.barTop = statusBarTop;
			this.header = this.header || {}
			if (getToken()) {
				this.header['Authorization'] = 'Bearer ' + getToken()
			}
			uni.getStorage({
				key: 'groupIdByIndex',
				success: (res) => {
					let data = JSON.parse(res.data);
					this.groupId = data.id;
				}
			});
			this.self = this; // 将组件实例赋值给self变量
		},
		methods: {
			submit() {
				uni.showLoading({
					title: "正在发布"
				})
				// 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
				let files = [];
				let sysFileInfos = []
				let index = 1;
				let type = '';
				if (!this.isPlaying) {
					files = this.$refs.uUpload.lists.filter(val => {
						return val.progress == 100;
					})
					console.log(files);
					files.forEach((element) => {
						const result = element.response;
						let temp = {
							fileIndex: index,
							fileName: result.newFileName,
							fileLocation: result.fileName,
							fileUrl: result.url
						}
						sysFileInfos.push(temp);
						index++;
					})
					type = 0;
				} else {
					let temp = {
						fileIndex: index,
						fileName: this.videoFile.newFileName,
						fileLocation: this.videoFile.fileName,
						fileUrl: this.videoFileUrl
					}
					sysFileInfos.push(temp);
					type = 1;
				}
				console.log(sysFileInfos);
				let formData = {
					content: this.value,
					locationInfo: this.locationInfo,
					locationDetail: this.locationDetail,
					sysFileInfos: sysFileInfos,
					groupId: this.groupId,
					type: type
				}
				addDaily(formData).then(res => {
					if (res.code == 200) {
						this.$store.commit('SET_PUBLISHCONTENTTYPE', 0)
						this.$store.commit('IS_REFRESH', true)
						this.$tab.switchTab('/pages/index')
						this.$modal.msgSuccess("发布成功")
					} else {
						this.$modal.msgError("发布失败")
					}
					uni.hideLoading()
				})
			},
			confirm() {
				let flag = false
				if (!this.isPlaying) {
					let fileArr = this.$refs.uUpload.lists;
					if (fileArr.length > 0 || this.value) {
						flag = true
					}
				} else {
					if (this.videoFileUrl || this.value) {
						flag = true
					}
				}
				if (flag) {
					this.$modal.confirm('确定放弃编辑内容吗？').then(() => {
						uni.navigateBack()
						this.value = ''
						this.videoFilePath = ''
						this.videoFileUrl = ''
						this.videoFile = {}
						this.isPlaying = false
					})
				} else {
					uni.navigateBack()
					this.value = ''
				}
			},
			getCurrentLocation() {
				const self = this.self; // 保存组件实例的引用
				uni.chooseLocation({
					success: function(res) {
						self.locationInfo = res.name // 使用self来访问组件实例的属性
						self.locationDetail = res.address // 使用self来访问组件实例的属性
					}
				})
			},
			removeVideo() {
				this.isPlaying = false
				this.videoFilePath = "";
				this.videoFileUrl = "";
				this.videoFile = {};
			},
			getVideo() {
				uni.chooseVideo({
					sourceType: ['album', 'camera'],
					maxDuration: 60,
					success: (res) => {
						console.log(res.tempFilePath); // 选择成功后的临时文件路径
						this.videoFilePath = res.tempFilePath; // 保存选择的视频文件路径
						this.getVideoFileInfo()
					},
				});

			},
			async getVideoFileInfo() {
				const fileInfo = await this.uploadVideo()
				const json = JSON.parse(fileInfo);
				this.videoFileUrl = json.url;
				this.videoFile.newFileName = json.newFileName;
				this.videoFile.fileName = json.fileName;
				this.isPlaying = true;
				// 根据接口返回的数据处理逻辑
			},
			uploadVideo() {
				return new Promise((resolve, reject) => {
					// 确保已选择视频文件
					if (!this.videoFilePath) {
						console.error('请先选择视频文件');
						return;
					}
					uni.showLoading({
						title: "加载中..."
					})
					// 上传视频文件
					uni.uploadFile({
						url: this.action, // 替换成你的上传接口地址
						filePath: this.videoFilePath,
						name: 'file',
						header: this.header,
						success: (uploadRes) => {
							const data = uploadRes.data;
							console.log('上传成功', data);
							uni.hideLoading();
							resolve(data);


						},
						fail: (uploadErr) => {
							console.error('上传失败', uploadErr);
							uni.hideLoading()
							this.$modal.msgError("上传失败")
							reject()
						},
					})
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		padding: 5rpx 15rpx;
	}

	.videoStyle {
		width: 150rpx;
		height: 200rpx;
	}
</style>